package com.haibeimohe.handler;

import com.alibaba.fastjson.JSONObject;
import com.haibeimohe.config.RpcRequest;
import com.haibeimohe.util.ApplicationContextFactory;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Method;

/**
 * 自定义服务端业务处理器
 * @author hassan
 */
public class UserServiceHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext context, Object msg) throws Exception {
        RpcRequest rpcRequest = (RpcRequest) msg;
        ApplicationContext applicationContext = ApplicationContextFactory.getApplicationContext();
        Object bean = applicationContext.getBean(rpcRequest.getRequestId());
        Method method = bean.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
        for (int i = 0, iLength = rpcRequest.getParameters().length; i < iLength; i++) {
            if (rpcRequest.getParameters()[i] instanceof JSONObject) {
                JSONObject jsonObject = (JSONObject) rpcRequest.getParameters()[i];
                rpcRequest.getParameters()[i] = jsonObject.toJavaObject(rpcRequest.getParameterTypes()[i]);
            }
        }
        Object result = method.invoke(bean, rpcRequest.getParameters());
        ByteBuf respByteBuf = Unpooled.copiedBuffer(result.toString().getBytes());
        context.writeAndFlush(respByteBuf);
    }
}
